<template>
  <div id="site-statistics-panel"></div>
</template>

<script lang="ts" setup>
  import * as echarts from 'echarts';
  import {onActivated, onMounted, onUnmounted, watch} from 'vue';
  import {statistic} from "@/api/site";
  import getThemeConfig, {mergeOptions} from "@/variable/echarts";

  const props = defineProps<{
    modelValue: boolean
  }>()

  let myChart: any
  let option = mergeOptions(getThemeConfig(), {
    toolbox: {
      show: false,
      feature: {
        dataView: {show: true, readOnly: false},
        magicType: {show: true, type: ['line', 'bar']},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    grid: {
      left: '30',
      right: '10',
      bottom: '20',
      top: '80',
      containLabel: true
    },
    calculable: true,
    xAxis: [{
      type: 'category',
      name: '地区',
      axisLabel: {
        color: '#3AECFF'
      },
    }],
    yAxis: {
      name: '数量',
      type: 'value',
      minInterval: 1,
    },
    series: [
      {
        name: '站点数量',
        type: 'bar',
        data: []
      },
      {
        name: '在线站点数量',
        type: 'bar',
        data: []
      }
    ]
  });
  const initEcharts = () => {
    const chartDom = document.getElementById('site-statistics-panel')
    if (chartDom == null) {
      return
    }
    chartDom.removeAttribute('_echarts_instance_')
    myChart = echarts.init(chartDom);
    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize)
  }

  onMounted(() => {
    initEcharts()
    initData()
  })

  onUnmounted(() => {
    window.removeEventListener("resize", myChart?.resize)
  })
  onActivated(() => {
    initEcharts()
  })

  const initData = () => {
    statistic().then(res => {
      const xData: any[] = []
      const yData1: any[] = []
      const yData2: any[] = []
      res.data.forEach((d: { regionName: any; offline: any; online: any; }) => {
        xData.push(d.regionName)
        yData1.push(d.offline + d.online)
        yData2.push(d.online)
      })
      myChart.setOption({
        xAxis: [
          {
            type: 'category',
            // prettier-ignore
            data: xData
          }
        ],
        series: [
          {
            name: '站点数量',
            type: 'bar',
            data: yData1
          },
          {
            name: '在线站点数量',
            type: 'bar',
            data: yData2
          }
        ]
      })
    })
  }
</script>

<style scoped lang="scss">
  #site-statistics-panel {
    width: 100%;
    height: 100%;
    /*min-width: 400px;*/
    /*min-height: 400px;*/
  }
</style>
